package com.ics.cmsadmin.agent;

import com.ics.cmsadmin.frame.constant.Constants;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.OrderStatusEnum;
import com.ics.cmsadmin.frame.core.enums.PayMethodEnum;
import com.ics.cmsadmin.frame.utils.KeyUtil;
import com.ics.cmsadmin.modules.agent.bean.AgentAccountBean;
import com.ics.cmsadmin.modules.agent.bean.AgentInfoBean;
import com.ics.cmsadmin.modules.agent.dao.AgentInfoDao;
import com.ics.cmsadmin.modules.agent.steward.AgentRepositories;
import com.ics.cmsadmin.modules.auth.bean.SysUser;
import com.ics.cmsadmin.modules.basic.bean.OrderBean;
import com.ics.cmsadmin.modules.basic.bean.StudentBean;
import com.ics.cmsadmin.modules.basic.dao.OrderDao;
import com.ics.cmsadmin.modules.basic.service.StudentService;
import com.ics.cmsadmin.modules.system.emums.SequenceNumberEnum;
import com.ics.cmsadmin.modules.system.service.SequenceNumberService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ics.cmsadmin.modules.agent.steward.AgentServices.*;
import static com.ics.cmsadmin.modules.auth.steward.AuthServices.userService;

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"spring.profiles.active=lvsw"})
public class GenerateAgentData {

    @Resource(name = "newStudentService")
    private StudentService studentService;

    @Resource
    private OrderDao orderDao;
    @Resource
    private AgentInfoDao agentInfoDao;
    @Resource
    private SequenceNumberService sequenceNumberService;


    @Test
    public void test1() {
        for (int i = 1; i <= 25; i ++){
            String date = "2018-11-"  + StringUtils.leftPad(i + "", 2, "0");
            agentDaySummaryService.daySummary(date);
        }
    }
    @Test
    public void generate2() throws InterruptedException {
//        for (int i = 1; i <= 21; i ++) {
            String date = "2018-11-25" ;
            doEveryDate(date);
            System.out.println("====> " + date);
//        }
    }

    private void doEveryDate(String date) {
        // 修改当前时间
        try {
            Runtime.getRuntime().exec("cmd /c date " + date);
        } catch (IOException e) {
            e.printStackTrace();
        }
        doExistStudent();
        doExistAgent();
        doMakeNewAgent("0");
        agentDaySummaryService.daySummary();
    }

    private void doMakeNewAgent(String parentId) {
//        buildAgents(parentId, RandomUtils.nextInt(1, 3))
//            .stream()
//            .parallel()
//            .filter(item -> RandomUtils.nextBoolean())
//            .forEach(item -> studentBuyOrder(buildStudents(item, RandomUtils.nextInt(1, 3))));
    }

    private void doExistAgent() {
        long agentCount = agentInfoDao.count(new AgentInfoBean());
        for (long i = 0, len = agentCount / 10; i <= len / 4 + 1; i ++){
            List<AgentInfoBean> agentInfoBeans = agentInfoDao.list(new AgentInfoBean(), new PageBean(RandomUtils.nextInt(1, ((int) len) + 1), 10));
            Optional.ofNullable(agentInfoBeans)
                .orElse(new ArrayList<>())
                .stream()
                .parallel()
                .filter(item -> RandomUtils.nextBoolean())
                .forEach(item -> studentBuyOrder(buildStudents(item, RandomUtils.nextInt(1, 3))));

            Optional.ofNullable(agentInfoBeans)
                .orElse(new ArrayList<>())
                .stream()
                .parallel()
                .filter(item -> RandomUtils.nextBoolean())
                .forEach(item -> doMakeNewAgent(item.getAgentNo()));
        }
    }

    /**
     *  现有的学生随机购买订单
     */
    private void doExistStudent() {
        PageResult<StudentBean> studentList = studentService.list(new StudentBean(), new PageBean(1, 101));
        long totalCount = studentList.getTotalCount();
        for (long i = 0, len = totalCount / 10; i <= len / 4 + 1; i ++){
            PageResult<StudentBean> list = studentService.list(new StudentBean(), new PageBean(RandomUtils.nextInt(1, ((int) len) + 1), 10));
            studentBuyOrder(list.getDataList());
        }
    }

    private void studentBuyOrder(List<StudentBean> studentList){
        Optional.ofNullable(studentList)
            .orElse(new ArrayList<>())
            .stream()
            .parallel()
            .filter(item -> RandomUtils.nextBoolean())
            .forEach(item -> buildOrders(item, RandomUtils.nextInt(1, 3)));
    }

    private List<AgentInfoBean> buildAgents(String parentId, int count) {
        return Stream.iterate(0, i -> i + 1)
            .limit(count)
            .map(item -> buildAgent(parentId))
            .collect(Collectors.toList());
    }

    private AgentInfoBean buildAgent(String parentId) {
        String agentNo = sequenceNumberService.newSequenceNumber(SequenceNumberEnum.AGENT);
        SysUser userInfo = new SysUser();
        String usernme = agentNo + RandomStringUtils.random(8, "0123456789abcdefghijklmnopqrstuvwxyz");
        userInfo.setLoginName(agentNo);
        userInfo.setEmail(usernme + "@qq.com");
        userInfo.setMobilephone("1" + RandomStringUtils.random(8, "0123456789"));
        userInfo.setUserType(Constants.USER_TYPE_AGENT);      // 标识登陆用户为分销商
        userInfo.setOrgId("agent");
        userService.insert(userInfo);
        AgentInfoBean agentInfoBean = new AgentInfoBean();
        agentInfoBean.setAgentNo(agentNo);
        agentInfoBean.setUserId(userInfo.getUserId());
        agentInfoBean.setParentId(parentId);
        agentInfoBean.setAgentType(RandomUtils.nextInt(1, 3) + "");
        agentInfoBean.setName(agentNo);

        AgentRepositories.agentInfoDao.insert(agentInfoBean);
        agentAccountService.insert(AgentAccountBean
            .builder()
            .agentNo(agentNo)
            .build());
        return agentInfoBean;
    }
    private List<StudentBean> buildStudents(AgentInfoBean agentInfoBean, int count){
        return Stream.iterate(0, i -> i + 1)
            .limit(count)
            .map(item -> buildStudent(agentInfoBean))
            .collect(Collectors.toList());
    }

    private StudentBean buildStudent(AgentInfoBean agentInfoBean){
        StudentBean student = StudentBean.builder()
            .agentNo(agentInfoBean.getAgentNo())
            .openId(RandomStringUtils.random(32, "0123456789"))
            .unionId(RandomStringUtils.random(30, "0123456789"))
            .nickname(RandomStringUtils.random(8, "abcdefghigjkmnopqrst"))
            .avatar("")
            .gender("0")
            .build();
        return studentService.refreshStudentInfoByWechat(student);
    }

    private List<OrderBean> buildOrders(StudentBean student, int count) {
        return Stream.iterate(0, i -> i + 1)
            .limit(count)
            .map(item -> buildOrder(student))
            .collect(Collectors.toList());
    }

    private OrderBean buildOrder(StudentBean student){
        OrderBean order = new OrderBean();
        order.setId(KeyUtil.genUniqueKey());
        order.setOpenId(student.getOpenId());

        order.setCoursePrice(new BigDecimal(299));
        order.setDiscountPrice(new BigDecimal(100));
        order.setOrderAmount(new BigDecimal(199));
        order.setStatus(OrderStatusEnum.SUCCESS.getCode());
        // 默认使用微信支付
        order.setPaymentMethod(PayMethodEnum.WECHAT.getCode());
        order.setUserId(student.getId());
        order.setSalesman(student.getSalesman());
        order.setUserName(student.getUsername());
        order.setCourseName("adad");
        order.setCourseId("11");
        // 设置分销商信息
        order.setAgentNo(student.getAgentNo());
        orderDao.insert(order);
        shareDetailService.generateShareByOrderId(order.getId());
        return order;
    }
}
